package com.meirengu.webview.service.impl;

import com.meirengu.channel.service.CcicService;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.model.KwCcicFilter;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.KwCcicFilterService;
import com.meirengu.webview.service.KwCcicPushService;
import com.meirengu.webview.service.UserInfoService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * KwCcicFilter服务实现层
 *
 * @author Mao
 * @create Mon May 07 14:32:24 CST 2018
 */
@Service
public class KwCcicFilterServiceImpl extends BaseServiceImpl<KwCcicFilter> implements KwCcicFilterService {


    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    private KwCcicPushService kwCcicPushService;

    @Autowired
    private CcicService ccicService;


    Logger logger = LoggerFactory.getLogger(KwCcicFilterServiceImpl.class);


    /**
     * 发送大地接口
     * 过滤条件
     * 1 地区
     * 2 20到60
     * 3 大于2w
     * 4 房车寿3其一
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendCCIC(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            //校验是否有ayd发送成功的记录
            Map<String, Object> ccicParams = new HashMap<>();
            ccicParams.put("mobile", user.getMobile());
            ccicParams.put("code", 1);
            Integer count = kwCcicPushService.getCount(ccicParams);
            //已有成功发送记录
            if (!NumberUtil.isNullOrZero(count)) {
                return sendFlag;
            }

            String ccicIol = redisClient.get("iol-ccic");
            if ("N".equals(ccicIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                String ip = userInfo.getIp();

                Integer income = userInfo.getSalary();
                Integer salaryMethod = userInfo.getSalaryMethod();
                Integer credit = userInfo.getCredit();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer house = userInfo.getHouse();
                Integer car = userInfo.getCar();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer fund = userInfo.getFund();
                Integer occupation = userInfo.getOccupation();
                Date brithdayDate = userInfo.getBirthday();
                int age = 25;
                age = DateUtils.getAge(brithdayDate);


                KwCcicFilter kwCcicFilter = new KwCcicFilter();
                kwCcicFilter.setUserId(id);
                kwCcicFilter.setMobile(mobile);
                kwCcicFilter.setChannelCode("ccic");
                kwCcicFilter.setChannelName("大地保险");

                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("ccic");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwCcicFilter.setSuited("N");
                            kwCcicFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwCcicFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwCcicFilter.setSuited("N");
                            kwCcicFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwCcicFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwCcicFilter.setSuited("N");
                            kwCcicFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwCcicFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(house + "") ||
                                kwInterfaceConfig.getCarValue().contains(car + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance + "")) {
                            String gender = "男";
                            if (sex.intValue() == 1) {
                                gender = "女";
                            }
                            String birthDate = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                            String occupationStr = "白领";
                            //职业  0白领   1私企业主  2公务员
                            if (occupation.intValue() == 1) {
                                occupationStr = "私企业主";
                            } else if (occupation.intValue() == 2) {
                                occupationStr = "公务员";
                            }
                            String salaryStr = "20000";
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            if (income.intValue() == 1) {
                                salaryStr = "3000";
                            } else if (income.intValue() == 2) {
                                salaryStr = "5000";
                            } else if (income.intValue() == 3) {
                                salaryStr = "8000";
                            } else if (income.intValue() == 4) {
                                salaryStr = "10000";
                            }
                            String salaryType = "银行打卡";
                            //工资发放方式  1 银行转账  2 现金发放
                            if (salaryMethod.intValue() == 2) {
                                salaryType = "现金";
                            }
                            int mortgageTab = 1;
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (house.intValue() != 2) {
                                mortgageTab = 0;
                            }
                            int houseFundTab = 1;
                            //住房公积金   0无公积金   1一年以内    2一年以上
                            if (fund.intValue() == 0) {
                                houseFundTab = 0;
                            }
                            int insuranceTab = 1;
                            //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
                            if (lifeInsurance.intValue() == 1) {
                                insuranceTab = 0;
                            }
                            int autoLoanTab = 1;
                            //名下车   1 无车   2 有车贷    3有车无贷
                            if (car.intValue() != 2) {
                                autoLoanTab = 0;
                            }
                            int socialSecurityTab = 1;
                            //社保   0无社保   1一年以内    2一年以上
                            if (socialSecurity.intValue() == 0) {
                                socialSecurityTab = 0;
                            }
                            int houseTab = 1;
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (house.intValue() == 1) {
                                houseTab = 0;
                            }
                            int autoTab = 1;
                            //名下车   1 无车   2 有车贷    3有车无贷
                            if (car.intValue() == 1) {
                                autoTab = 0;
                            }
                            int creditTab = 1;
                            //信用情况 1无信用卡无贷款   2有信用卡或贷款
                            if (credit.intValue() == 1) {
                                creditTab = 0;
                            }
                            String provinceId = ConfigUtil.getConfig("C" + city);
                            String createdDate = DateUtils.dateToStr(userInfo.getCreateDate(), "yyyy-MM-dd");
                            Integer code = ccicService.applyLoan(name, mobile, gender, age, birthDate,
                                    createdDate, occupationStr, salaryStr, salaryType, mortgageTab,
                                    houseFundTab, insuranceTab, autoLoanTab, socialSecurityTab, houseTab,
                                    autoTab, creditTab, expectAmount.intValue() + "", provinceId);

                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "ccic", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                            kwCcicFilter.setSuited("Y");
                            kwCcicFilter.setCode(UserChannelEnum.PASS.getValue());
                        } else {
                            kwCcicFilter.setSuited("N");
                            kwCcicFilter.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            kwCcicFilter.setRefuseMsg("用户无房：" + house.intValue() + "  用户无车：" + car.intValue() + "  用户无寿险：" + lifeInsurance.intValue());
                        }
                    }

                }
                insert(kwCcicFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }



}
